import Vue from 'vue';
import axios from 'axios';
import qs from 'qs';
import { config } from './config';
const { result_code, requestExe, requestCAD, requestFront } = config;

const serviceExe = axios.create({
  baseURL: requestExe,
  timeout: config.request_timeout
});

const serviceCAD = axios.create({
  baseURL: requestCAD,
  timeout: config.request_timeout
});

const serviceFront = axios.create({
  baseURL: requestFront,
  timeout: config.request_timeout
});

const setupInterceptors = (service) => {
  service.interceptors.request.use(
    async (conf) => {
      if (
        conf.method === 'post' &&
        conf.headers['Content-Type'] === 'application/x-www-form-urlencoded'
      ) {
        conf.data = qs.stringify(conf.data);
      }
      if (conf.method === 'get' && conf.params) {
        let url = conf.url + '?';
        const keys = Object.keys(conf.params);
        for (const key of keys) {
          if (conf.params[key] !== void 0 && conf.params[key] !== null) {
            url += `${key}=${encodeURIComponent(conf.params[key])}&`;
          }
        }
        url = url.slice(0, -1);
        conf.params = {};
        conf.url = url;
      }
      return conf;
    },
    (error) => Promise.reject(error)
  );

  service.interceptors.response.use(
    (response) => {
      if (response.config.responseType === 'blob') {
        return response;
      } else if (response.data.code === result_code || response.data.success) {
        return response.data;
      } else {
        Vue.prototype.$message.error(response.data.message || JSON.stringify(response.data));
      }
    },
    (error) => {
      const status = error.response?.status;
      const errorMessage = error.response?.data?.message || error.message;
      if (status === 401) {
        // Vue.prototype.$message.error('你的账号已在另一台设备登录，请重新登陆');
      } else {
        Vue.prototype.$message.error(errorMessage);
      }
      return Promise.reject(error.response?.data);
    }
  );
};

setupInterceptors(serviceExe);
setupInterceptors(serviceCAD);
setupInterceptors(serviceFront);

export { serviceExe, serviceCAD, serviceFront };